package xin.sparrow.manage;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import xin.sparrow.bean.QiNiuConfig;

import java.io.File;
import java.io.InputStream;

/**
 * Created by wancheng on 2019/10/6.
 */
@Slf4j
public class QiNiuUploadManage {

    /**
     * 客户端上传七牛云
     * 获取简单的上传凭证
     * @return
     */
    public static String simpleUploadToken(){
        String accessKey = QiNiuConfig.getAccessKey();
        String secretKey = QiNiuConfig.getSecretKey();
        String bucket = QiNiuConfig.getBucket();
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        long expireSeconds = 3600;
        Auth auth = Auth.create(accessKey, secretKey);
        String token = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        log.info("get qiniu upload token,token = {}",token);
        return token;
    }

    /**
     * 上传七牛回调的上传token
     * @param callBackUrl 回调的url
     * @return
     */
    public static String callBackUploadToken(String callBackUrl){
        String accessKey = QiNiuConfig.getAccessKey();
        String secretKey = QiNiuConfig.getSecretKey();
        String bucket = QiNiuConfig.getBucket();
        StringMap putPolicy = new StringMap();
        putPolicy.put("callbackUrl", callBackUrl);
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        putPolicy.put("callbackBodyType", "application/json");
        long expireSeconds = 3600;
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket, null, expireSeconds, putPolicy);
    }

    /**
     * 文件路径上传,本地上传文件
     * @param filePath 文件路径
     * @param fileName 文件名
     */
    public static void filePathUpload(String filePath,String fileName){
        String token = simpleUploadToken();
        UploadManager uploadManager = getUploadManager();
        try {
            log.info("filePathUpload,filePath={},fileName={}",filePath,fileName);
            Response response = uploadManager.put(filePath, fileName, token);
            //解析上传成功的结果
            analysisResponse(response);
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString(),ex);
            try {
                log.error(r.bodyString(),ex);
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }
    /**
     * 文件路径上传,本地上传文件
     * @param bytes 文件路径
     * @param key 文件名
     */
    public static void bytesUpload(byte[] bytes,String key){
        String token = simpleUploadToken();
        UploadManager uploadManager = getUploadManager();
        try {
            log.info("bytesUpload,key={}",key);
            Response response = uploadManager.put(bytes, key, token);
            //解析上传成功的结果
            analysisResponse(response);
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString(),ex);
            try {
                log.error(r.bodyString(),ex);
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    public static void InputStreamUpload(InputStream inputStream, String key){
        String token = simpleUploadToken();
        UploadManager uploadManager = getUploadManager();
        try {
            log.info("inputStream,key={}",key);
            Response response = uploadManager.put(inputStream, key, token,null, null);
            //解析上传成功的结果
            analysisResponse(response);
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString(),ex);
            try {
                log.error(r.bodyString(),ex);
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }
    /**
     * 获取上传的 UploadManager
     * @return UploadManager
     */
    private static UploadManager getUploadManager(){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        return new UploadManager(cfg);
    }

    /**
     * 解析返回结果
     * @param response
     * @throws QiniuException
     */
    private static void analysisResponse(Response response) throws QiniuException {
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info("putRet.key={},putRet.hash={}",putRet.key,putRet.hash);
    }

}
